package com.leetcode.LC;

public class LC1694 {
    public String reformatNumber(String number) {
        StringBuilder builder = new StringBuilder();
        String replace = number.replace(" ", "").replace("-", "");

        if (replace.length()<=3){
            return replace;
        }else if (replace.length()==4){
            return builder.append(replace.substring(replace.length() - 4, replace.length() - 2) + "-" + replace.substring(replace.length() - 2, replace.length())).toString();
        }

        if (replace.length() % 3 == 1) {
            for (int i = 0; i < replace.length() - 4; i++) {
                builder.append(replace.charAt(i));
                if (i != 0 && i % 3 == 2) {
                    builder.append("-");
                }
            }
            builder.append(replace.substring(replace.length() - 4, replace.length() - 2) + "-" + replace.substring(replace.length() - 2, replace.length()));
        } else if (replace.length() % 3 == 0) {
            for (int i = 0; i < replace.length(); i++) {
                builder.append(replace.charAt(i));
                if (i != 0 && i != replace.length() - 1 && i % 3 == 2) {
                    builder.append("-");
                }
            }
        }else if (replace.length() % 3 == 2) {
            for (int i = 0; i < replace.length()-2; i++) {
                builder.append(replace.charAt(i));
                if (i != 0 && i % 3 == 2) {
                    builder.append("-");
                }
            }
            builder.append(replace.substring(replace.length() - 2, replace.length()));
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        System.out.println(new LC1694().reformatNumber("123 4"));
    }
}
